import ElInput from "element-plus/es/components/input";
import { defineComponent } from "vue";
import i18n from "@/languages/index";
const { t } = i18n.global;
export default defineComponent({
	props: {
		modelValue: [String, Number],
		sufixBtn: {
			type: Boolean,
			default() {
				return true;
			}
		},
		btnText: {
			type: String,
			default: t("autosaveinput.btntext.default")
		},
		placeholder: {
			type: String,
			default: ""
		},
		empty: {
			type: String,
			default: t("autosaveinput.empty.default")
		},
		minHeight: {
			type: [String, Number],
			default() {
				return "30px";
			}
		}
	},
	emits: ["change", "update:modelValue"],

	setup(props, { emit, attrs, expose }) {
		//原始值，用于变更比较
		let old: any = null;
		//实时输入值，用于model绑定
		type FormInstance = InstanceType<typeof ElInput>;
		const inputRef = ref<FormInstance>();
		const inputValue: any = ref();
		//是否显示输入框状态
		const showInput = ref<boolean>(false);
		//内容是否变化
		const isChange = ref<boolean>(false);
		watchEffect(() => {
			inputValue.value = props.modelValue;
			if (!old) {
				old = props.modelValue;
			}
		});

		//输入框失去焦点：内容没有改变，则切回到文本模式
		const onBlurInput = () => {
			showInput.value = isChange.value;
		};
		//输入框内容改变
		const onChangeInput = () => {
			emit("update:modelValue", inputValue.value);
			isChange.value = old != inputValue.value;
		};
		//提交输入框内容
		const onSubmit = () => {
			old = inputValue.value;
			isChange.value = false;
			showInput.value = false;
			emit("change");
		};
		const reset = () => {
			showInput.value = false;
		};
		function focus() {
			showInput.value = true;
			nextTick(() => {
				(inputRef.value as FormInstance).focus();
			});
		}
		function unFocus() {
			showInput.value = false;
		}
		expose({ focus, unFocus });
		return () => {
			return (
				<div class="auto-save-input h-full w-full flex" style={`min-height:${props.minHeight}`}>
					{showInput.value ? (
						<el-input
							ref={inputRef}
							class="flex-1"
							v-model={inputValue.value}
							placeholder={props.placeholder}
							{...attrs}
							onInput={() => onChangeInput()}
							onBlur={() => onBlurInput()}
						>
							{{
								suffix: () => {
									return (
										<>
											{isChange.value ? (
												<el-link type="primary" class="iconfont iconcheck1" onClick={() => onSubmit()}>
													{t("autosaveinput.link.save")}
												</el-link>
											) : (
												<el-link class="iconfont" onClick={() => reset()}>
													{t("autosaveinput.link.cancel")}
												</el-link>
											)}
										</>
									);
								}
							}}
						</el-input>
					) : (
						<div class="flex-1" onClick={() => (showInput.value = true)}>
							{inputValue.value || props.empty}
						</div>
					)}
					{props.sufixBtn && !showInput.value ? (
						<el-link type="primary" class="setting-btn" onClick={() => (showInput.value = true)}>
							{props.btnText}
						</el-link>
					) : null}
				</div>
			);
		};
	}
});
